/*
 * @lc app=leetcode.cn id=114 lang=cpp
 *
 * [114] 二叉树展开为链表
 */
struct TreeNode {
    int val;
    TreeNode *left;
    TreeNode *right;
    TreeNode() : val(0), left(nullptr), right(nullptr) {}
    TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
    TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
};
// @lc code=start
/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution
{
  public:
    void flatten(TreeNode *root)
    {
        TreeNode *head = root;

        while (head) {
            /* 找到左子树的最右节点 */
            TreeNode *right_subtree_right_node = head->left;
            while (right_subtree_right_node && right_subtree_right_node->right) {
                right_subtree_right_node = right_subtree_right_node->right;
            }
            /* 左子树的最右节点的右孩子，应该是当前节点的右子树的根结点 */
            if (right_subtree_right_node) {
                right_subtree_right_node->right = head->right;
            }
            if (head->left) {
                head->right = head->left;
            }
            head->left = nullptr;
            head = head->right;
        }
    }
};
// @lc code=end
